package com.zhoukai.service.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhoukai.constants.Constants;
import com.zhoukai.domain.*;
import com.zhoukai.dto.PurchaseDto;
import com.zhoukai.dto.PurchaseFormDto;
import com.zhoukai.dto.PurchaseItemDto;
import com.zhoukai.mapper.InventoryLogMapper;
import com.zhoukai.mapper.MedicinesMapper;
import com.zhoukai.mapper.PurchaseItemMapper;
import com.zhoukai.utils.IdGeneratorSnowflake;
import com.zhoukai.vo.DataGridView;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhoukai.mapper.PurchaseMapper;
import com.zhoukai.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;

/**
 * Created with IntelliJ IDEA.
 * @Author: zk
 * @Date: 2022/02/09/15:23
 * @Description:
 */
@DubboService
@Transactional
public class PurchaseServiceImpl implements PurchaseService{
    @Autowired
    private PurchaseMapper purchaseMapper;

    @Autowired
    private PurchaseItemMapper purchaseItemMapper;

    @Autowired
    private InventoryLogMapper inventoryLogMapper;

    @Autowired
    private MedicinesMapper medicinesMapper;



    @Override
    public DataGridView listPurchasePage(PurchaseDto purchaseDto) {
        Page<Purchase> page=new Page<>(purchaseDto.getPageNum(),purchaseDto.getPageSize());
        this.purchaseMapper.selectPage(page,Wrappers.lambdaQuery(Purchase.class)
            .like(StringUtils.isNotBlank(purchaseDto.getApplyUserName()),Purchase::getApplyUserName,purchaseDto.getApplyUserName())
            .eq(StringUtils.isNotBlank(purchaseDto.getPurchaseId()),Purchase::getPurchaseId,purchaseDto.getPurchaseId())
            .eq(StringUtils.isNotBlank(purchaseDto.getStatus()),Purchase::getStatus,purchaseDto.getStatus())
            .orderByDesc(Purchase::getCreateTime));
        return new DataGridView(page.getTotal(),page.getRecords());

    }

    @Override
    public Purchase getPurchaseById(String purchaseId) {
        return this.purchaseMapper.selectById(purchaseId);
    }

    @Override
    public int doAudit(String purchaseId, SimpleUser simpleUser) {
        Purchase purchase = this.purchaseMapper.selectById(purchaseId);
        //只有是状态为未提交1  或者审核失败4 的状态才能提交审核
        if (purchase.getStatus().equals(Constants.STOCK_PURCHASE_STATUS_1) || purchase.getStatus().equals(Constants.STOCK_PURCHASE_STATUS_4)){
            purchase.setStatus(Constants.STOCK_PURCHASE_STATUS_2);
            purchase.setApplyUserId(Long.valueOf(simpleUser.getUserId().toString()));//设置申请人
            purchase.setApplyUserName(simpleUser.getUserName());//设置申请人名
            return this.purchaseMapper.updateById(purchase);

        }
        return 0;
    }

    @Override
    public int doInvalid(String purchaseId) {
        Purchase purchase = this.purchaseMapper.selectById(purchaseId);
        //只有是状态为未提交1  或者审核失败4 的状态才能作废
        if (purchase.getStatus().equals(Constants.STOCK_PURCHASE_STATUS_1) || purchase.getStatus().equals(Constants.STOCK_PURCHASE_STATUS_4)){
            purchase.setStatus(Constants.STOCK_PURCHASE_STATUS_5);
            return this.purchaseMapper.updateById(purchase);

        }
        return 0;
    }

    @Override
    public int auditPass(String purchaseId) {
        Purchase purchase = this.purchaseMapper.selectById(purchaseId);
        purchase.setStatus(Constants.STOCK_PURCHASE_STATUS_3);//设置状态为审核通过
        return this.purchaseMapper.updateById(purchase);

    }

    @Override
    public int auditNoPass(String purchaseId, String auditMsg) {
        Purchase purchase = this.purchaseMapper.selectById(purchaseId);
        purchase.setStatus(Constants.STOCK_PURCHASE_STATUS_4);//设置状态为审核不通过
        purchase.setAuditMsg(auditMsg);
        return this.purchaseMapper.updateById(purchase);

    }

    @Override
    public List<PurchaseItem> getPurchaseItemById(String purchaseId) {
        if(null!=purchaseId){
            QueryWrapper<PurchaseItem> qw=new QueryWrapper<>();
            qw.eq(PurchaseItem.COL_PURCHASE_ID,purchaseId);
            return purchaseItemMapper.selectList(qw);
        }
        return Collections.EMPTY_LIST;

    }

    /**
     * 暂存   采购单的状态是Constants.STOCK_PURCHASE_STATUS_1
     * @param purchaseFormDto
     * @return
     */
    @Override
    public int addPurchaseAndItem(PurchaseFormDto purchaseFormDto) {
        Purchase purchase = this.purchaseMapper.selectById(purchaseFormDto.getPurchaseDto().getPurchaseId());
        if(null!=purchase){
            //删除之前的数据
            this.purchaseMapper.deleteById(purchase.getPurchaseId());
            //删除之前的详情数据
            QueryWrapper<PurchaseItem> qw=new QueryWrapper<>();
            qw.eq(PurchaseItem.COL_PURCHASE_ID,purchase.getPurchaseId());
            this.purchaseItemMapper.delete(qw);
        }
        //保存采购单主表数据
        Purchase newPurchase=new Purchase();
        BeanUtil.copyProperties(purchaseFormDto.getPurchaseDto(),newPurchase);
        newPurchase.setStatus(Constants.STOCK_PURCHASE_STATUS_1);//未提交状态
        newPurchase.setCreateBy(purchaseFormDto.getPurchaseDto().getSimpleUser().getUserName());
        newPurchase.setCreateTime(DateUtil.date());
        int a=this.purchaseMapper.insert(newPurchase);
        //保存详情数据
        for (PurchaseItemDto item : purchaseFormDto.getPurchaseItemDtos()) {
            PurchaseItem purchaseItem=new PurchaseItem();
            BeanUtil.copyProperties(item,purchaseItem);
            purchaseItem.setPurchaseId(newPurchase.getPurchaseId());
            purchaseItem.setItemId(IdGeneratorSnowflake.snowflakeId().toString());
            this.purchaseItemMapper.insert(purchaseItem);
        }
        return a;
    }


    @Override
    public int addPurchaseAndItemToAudit(PurchaseFormDto purchaseFormDto) {
        String purchaseId = purchaseFormDto.getPurchaseDto().getPurchaseId();
        Purchase purchase = this.purchaseMapper.selectById(purchaseId);
        if(null!=purchase){
            //先删除
            this.purchaseMapper.deleteById(purchaseId);
            //再删除详情表
            QueryWrapper<PurchaseItem> qw=new QueryWrapper<>();
            qw.eq(PurchaseItem.COL_PURCHASE_ID,purchaseId);
            this.purchaseItemMapper.delete(qw);
        }
        //保存采购单主表数据
        Purchase newPurchase=new Purchase();
        BeanUtil.copyProperties(purchaseFormDto.getPurchaseDto(),newPurchase);
        newPurchase.setCreateTime(DateUtil.date());
        newPurchase.setCreateBy(purchaseFormDto.getPurchaseDto().getSimpleUser().getUserName());
        //设置状态为待审核
        newPurchase.setStatus(Constants.STOCK_PURCHASE_STATUS_2);
        //设置申请人
        newPurchase.setApplyUserName(purchaseFormDto.getPurchaseDto().getSimpleUser().getUserName());
        newPurchase.setApplyUserId(Long.valueOf(purchaseFormDto.getPurchaseDto().getSimpleUser().getUserId().toString()));
        int i = this.purchaseMapper.insert(newPurchase);
        //保存采购单位详情数据
        List<PurchaseItemDto> purchaseItemDtos = purchaseFormDto.getPurchaseItemDtos();
        for (PurchaseItemDto item : purchaseItemDtos) {
            PurchaseItem purchaseItem=new PurchaseItem();
            BeanUtil.copyProperties(item,purchaseItem);
            purchaseItem.setPurchaseId(newPurchase.getPurchaseId());
            purchaseItem.setItemId(IdGeneratorSnowflake.snowflakeId().toString());
            this.purchaseItemMapper.insert(purchaseItem);
        }
        return i;

    }

    @Override
    public int doInventory(String purchaseId, SimpleUser currentSimpleUser) {
        Purchase purchase = this.purchaseMapper.selectById(purchaseId);
        List<PurchaseItem> purchaseItems = this.getPurchaseItemById(purchaseId);
        if(null!=purchaseItems&&!purchaseItems.isEmpty()){
            for (PurchaseItem item : purchaseItems) {
                InventoryLog inventoryLog=new InventoryLog();
                inventoryLog.setInventoryLogId(IdGeneratorSnowflake.snowflakeId().toString());
                inventoryLog.setPurchaseId(purchaseId);//单据号
                inventoryLog.setMedicinesId(item.getMedicinesId());
                inventoryLog.setMedicinesName(item.getMedicinesName());
                inventoryLog.setMedicinesType(item.getMedicinesType());
                inventoryLog.setPrescriptionType(item.getPrescriptionType());
                inventoryLog.setInventoryLogNum(item.getPurchaseNumber());
                inventoryLog.setTradePrice(item.getTradePrice());
                inventoryLog.setTradeTotalAmount(item.getTradeTotalAmount());
                inventoryLog.setBatchNumber(item.getBatchNumber());
                inventoryLog.setProducterId(item.getProducterId());
                inventoryLog.setConversion(item.getConversion());
                inventoryLog.setUnit(item.getUnit());
                inventoryLog.setCreateTime(DateUtil.date());
                inventoryLog.setCreateBy(currentSimpleUser.getUserName());
                inventoryLogMapper.insert(inventoryLog);
                //更新药品库存
                Medicines medicines = medicinesMapper.selectById(inventoryLog.getMedicinesId());
                medicines.setMedicinesStockNum(medicines.getMedicinesStockNum()+item.getPurchaseNumber());
                this.medicinesMapper.updateById(medicines);
            }
            //更新单据状态
            purchase.setStatus(Constants.STOCK_PURCHASE_STATUS_6);
            purchase.setStorageOptUser(currentSimpleUser.getUserName());
            purchase.setStorageOptTime(DateUtil.date());
            return this.purchaseMapper.updateById(purchase);
        }
        return 0;

    }


}

